package com.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.gulimall.order.entity.OrderEntity;
import com.gulimall.order.vo.PayVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Slf4j
@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayTemplate {

    //在支付宝创建的应用的id
    private   String app_id = "2016102400750284";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private  String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJcTLQ594oHSa0CKeJ/tY4cx9KiOcwE4gf2QW8UIttAU82ek7N1O0JoKItcQ6OgP0WIPKPytMkmZzirXci0Ar6HQrcC75TXCQWT2fvcQwasdbVrMjVQWQAg6RLbMszbfMraE0u2e1JFhbqv1jyXHiVCTMGiLhceqXKcyhRp/uz5WQgchzhd3sO7o9Bov8yAy5dxYzaMOLOjgHQ/YhEc7wDH4ut/E2ITgeOvQwVfJgZaiBNN9mlqqshFjAdOdgZ3WWtyCExFrIP6pd3rDhWY2a+2EXy1/8iAsZSdn8WmzRaLbSsipQZ1GD9X+O2b5862nc9u0aHcU5y5k5Fe0D/SGM9AgMBAAECggEASUfNxaNj9NHN/5ZaZF/5TCXND09IUvv3/CX16TCf1/Ku/1F1E3nPFT6DYOaM9hhEeWVY+Cg/sUPUh7205kwqghxIlA4NmcOeOSN/2uIUFi31yluF39Ze67T38pxMO5RW7saNtWp/4KORiKo9UEWFdCoZjtnzv2i6oTBNTY8/iIxXKd2MJ64Pp16a79EO5F6YQJoHON9OwMbyt1DHDEMPN5kSb+aBR6yDzt7E0EQmr4aWw1CR8siwKlI3bs3kEblkb7J/WMjrbui5DApE4mBeHE0zycxN5zH2YnQ8Rzm1apvHnSa79FMPG8uUUgM83Ko/ZUZvgnsCQM/3ocDgA+xBfQKBgQD9nrCq+hZbLMkkAtxgQbA5JN6Fbb0NrhmNG+2yg3fA8ZxcrP2gUn2BNFT0X5z1ZoY1uLm6U5XwmK+Wj5nCBJT7KGfhQdSoZirG4pz7MHKHPaCcFjvTgdwwfXtEnyTRyiuuUNUxxXzGj4gfTExSv5N4uY2VFyp/9Qon4o+2R5qiIwKBgQDLVSdmcbOTmZ7I+JJ4cGu77FmBsjMWbCYeSV37Frl58zJOW8tZE90i9bvGlgEQFpk+FsgXnimHP7vkkTrRwzr4fAuoJxd4guMyQYFZrq8kSLC1t17Om/8jnAV5odg+EnLa9O7qhvMHP197KmnsMlsQAKnmTTvK3/rKdosY7l/LHwKBgQC1FT4dBe06cjK3VJeW3q/9TRbYe+8VOm6h8wP3hqjViW1UOmvosZ1MyFm0FiSSjv5akyeBIzcWj14niSaGghEBduscyY0WI8R9NsZRD1lmuJjZeYKD1N+re5ys9VgrtkcT8kEWhWQ+vbK6bha8qm6YLxwpDF5a+FGlAr4Lrvp4swKBgA58YZM11IJWdm6A7wZvk+1OeE36IROe3tRXi7+ArfQXNGVKuuD8vktoUFlkhGzd/0riGp08Il9FViCBjDw3eXMMe1QefNiUEpWY/xshi8688wHvL2zuxi2GRwmUUzCQ5efdfUvuE1BX3niK3AL8z2oDchc7N2BLtrVH3r8G9IInAoGBALN9S+kt/SXPGiO3F2oRhVnJHzjaDE/ZOSaRH/0ftFXXv7fq80NkDLhkUc0301Licxl7glmY9/7Usw2rLKm0nyBLnsNdzl6GSFOrtNBay6+TYGN16IKFz6ffA4Rr8abjb9zb+memSz8i7AYJ4nHT2s952D2F49w25WgiY4v0t/i3";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private  String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAodcGY3b8QasK5xY1/Ta/7Kj+b1Bw5Rz6WJPnJyfriob4MjSYskrW0qUXPS4J6+emEpsxHl9kfZTvNU78QIc2IoVQd4FUJYNekNQDZQyFgPJ6+TpxB/E6n6Ns5zVAKJ8sZwhdZhABeHki55IBUjOB67k/snRn4ymo2qeVZEhfRNC0rXtzd1TL7sd2JWuHwAABQ1wHGmVgvcMhJB635M89lXy/dcH3gRE4i4lzTFXytaHlBtWRJTkQ5z4lndjyjn8JxgoGrvRlqeSJICkJ9Jaoj1pNH7ThZEKOW3lDQp2CtGdFXztmNaN+LUy7863XtwJje3qbEcnFUWeGkvn0zPDi5wIDAQAB";
    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private  String notify_url = "http://mx4a65jp98.bjhttp.cn/payed/notify";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    private  String return_url = "http://member.gulimall.com/memberOrder.html";

    // 签名方式
    private  String sign_type = "RSA2";

    // 字符编码格式
    private  String charset = "utf-8";

    //订单超时时间
    private String timeout = "2m";

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private  String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    public  String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        log.info("发送订单的订单号："+out_trade_no);
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+timeout+"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        System.out.println("支付宝的响应："+result);

        return result;

    }

    /**
     * 支付宝交易关闭
     * @param orderEntity
     */
    public void closeOrder(OrderEntity orderEntity) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);
        AlipayTradeCloseRequest alipay_request=new AlipayTradeCloseRequest();

        AlipayTradeCloseModel model =new AlipayTradeCloseModel();
        log.info("发送关闭订单的订单号："+orderEntity.getOrderSn());
        model.setOutTradeNo(orderEntity.getOrderSn());      //商户订单号，和支付宝交易号二选一
//            model.setTradeNo(trade_no);             //支付宝交易号，和商户订单号二选一
        alipay_request.setBizModel(model);

        AlipayTradeCloseResponse alipay_response=alipayClient.execute(alipay_request);
        System.out.println(alipay_response.getBody());
    }
}
